import GameMap from "./Map/GameMap";
import gConfigManager from "./ConfigManager";
import { ConfigType } from "./Common/GameDefine";
import MonsterConfig from "./Config/MonsterConfig";
import Monster from "./Monster/Monster";
import MapConfig from "./Config/MapConfig";

export default class MapManager {
    //保存所有地图 <mapId, GameMap>
    m_maps: Map<number, GameMap> = new Map<number, GameMap>();

    public init(): void {
        //读取配置
        let mapCfg = (<MapConfig>gConfigManager.getConfigByType(ConfigType.CT_MAP)).getAllCfg();
        if (mapCfg) {
            mapCfg.forEach((val, key) => {
                this.createMapByCfg(val);
            });
        }
    }

    public getMapById(mapId: number): GameMap {
        return this.m_maps.get(mapId);
    }

    private createMapByCfg(cfg): void {

        let monsterCfg: MonsterConfig = <MonsterConfig>gConfigManager.getConfigByType(ConfigType.CT_MONSTER);
        if (!monsterCfg) {
            console.error("Monster config not exist.");
            return;
        }

        if (!cfg || this.m_maps.has(cfg.id)) {
            cc.error("cfg is null or map existed.");
            return;
        }

        let map: GameMap = new GameMap();
        map.m_mapId = cfg.id;
        map.m_mapName = cfg.name;
        map.m_minLevel = cfg.min_level;
        map.m_maxLevel = cfg.max_level;

        //将怪物id转换成对象
        cfg.monsterIds.forEach((monsterId, key) => {
            let mCfg = monsterCfg.getCfgById(monsterId);
            if (!mCfg) {
                console.error("Monster not exist. mapId=%d, monsterId=%d", cfg.id, monsterId);
            }
            else {
                let monster = this.createMonsterByCfg(mCfg);
                monster.m_monsterMg = map.m_monsterMg;
                map.m_monsterMg.addMonster(monster);
            }
        });

        this.addMap(map);
    }

    private createMonsterByCfg(cfg): Monster {
        let monster: Monster = new Monster();
        monster.m_id = cfg.id;
        monster.m_name = cfg.name;
        monster.m_baseAttr.m_hp = cfg.hp;
        return monster;
    }

    private addMap(map: GameMap): void {
        if(map){
            this.m_maps.set(map.m_mapId, map);
        }
    }
}